from typing import Any

import xmltodict
import json
import yaml
import jmespath

from config_params.解析xml为yaml.test_plan import TestPlan
from config_params.解析xml为yaml.utils import jme

with open('/Users/anxiaodong/PycharmProjects/jmeter-api/example_testplan_04.jmx', 'r') as f:
    data1 = f.read()
data_dict = xmltodict.parse(data1)
ss = json.dumps(data_dict, ensure_ascii=False, indent=2)
with open('1.json', "w", encoding="utf-8") as f:
    f.write(ss)


#
class parseJmeterXmlToYaml:
    
    def jm_xml_to_json(self, file_name):
        with open(file_name, 'r', encoding="utf-8") as f:
            return json.loads(f.read().replace("@", "").replace("#", ""))
    
    def gener_test_plan_yaml(self, file_name):
        res = self.jm_xml_to_json(file_name)
        result_dict = TestPlan.genre_test_plan(res)
        test_plan_dict = result_dict["jmeterTestPlan"]
    
        configElement_list = []
        test_plan_next_ele_data = jme("jmeterTestPlan.hashTree.hashTree", res)
        if test_plan_next_ele_data is not None:
            cacheManager_dict = {}
            cacheManager_res = jme("CacheManager", test_plan_next_ele_data)
            if cacheManager_res is not None:
                cacheManager_dict["name"] = jme("testname", cacheManager_res)
                cacheManager_dict["type"] = "HTTPCacheManager" if jme("testclass", cacheManager_res) == "CacheManager" else ""
                cacheManager_dict["clear_each_iteration"] = bool(jme("boolProp[?name==`clearEachIteration`]|[0].text",
                                                                cacheManager_res))
                cacheManager_dict["use_cache_control"] = bool(jme("boolProp[?name==`useExpires`]|[0].text", cacheManager_res))
                cacheManager_dict["max_elements_in_cache"] = int(jme("intProp.text", cacheManager_res))
                cacheManager_dict["comments"] = jme("stringProp.text", cacheManager_res)
                cacheManager_dict["is_enabled"] = bool(jme("enabled", cacheManager_res))
                configElement_list.append(cacheManager_dict)
    
                test_plan_dict["testPlan"]["configElement"] = configElement_list
            print()
    
        result_dict["jmeterTestPlan"] = test_plan_dict
        # ss = json.dumps(result_dict)
        yaml_data = yaml.dump(result_dict, indent=2, sort_keys=False, allow_unicode=True, default_flow_style=False)
        with open("jm.yaml", "w", encoding="utf-8") as f:
            f.write(yaml_data)

    # print(test_plan)
# xml_data = xmltodict.unparse(data_dict, pretty=True)
# print(xml_data)
# 
# with open('/Users/anxiaodong/PycharmProjects/jmeter-api/example_testplan_05.jmx', "w", encoding="utf-8") as f:
#     f.write(xml_data)
if __name__ == "__main__":
    parseJmeterXmlToYaml().gener_test_plan_yaml("1.json")
